package com.woniu.inlet.timer;

import com.woniu.outlet.dao.PotentialMessageMapper;
import com.woniu.outlet.po.PotentialMessage;
import com.woniu.outlet.po.PotentialMessageExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class PotentialCustomerTimer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PotentialMessageMapper potentialMessageMapper;

    @Scheduled(fixedRate = 20000)//每隔20秒扫描一次
    public void aaaa(){
        log.info("定时器 开始工作了");
        //获得没有发送的消息
        PotentialMessageExample example = new PotentialMessageExample();
        PotentialMessageExample.Criteria criteria = example.createCriteria();
        criteria.andPotentialmessageStatusEqualTo(0);
        criteria.andPotentialmessageCountGreaterThan(0);

        List<PotentialMessage> potentialMessages = potentialMessageMapper.selectByExample(example);

        if(potentialMessages.size()>0){
            for(PotentialMessage potentialMessage: potentialMessages){
                //将消息message的id存到corralate
                CorrelationData data = new CorrelationData();
                data.setId(potentialMessage.getPotentialmessageId().toString());

                //将消息发送到队列
                rabbitTemplate.convertAndSend(potentialMessage.getPotentialmessageExchange(),potentialMessage.getPotentialmessageKey()
                            ,potentialMessage.getPotentialmessageContext(),data);

                //修改重复尝试的次数
                potentialMessage.setPotentialmessageCount(potentialMessage.getPotentialmessageCount()-1);
                potentialMessageMapper.updateByPrimaryKeySelective(potentialMessage);
            }

        }


    }


}
